<template>
  <!-- 异常品通知单表单弹窗 -->
  <div>
    <el-dialog
      v-model="visible"
      :title="dialogTitle"
      width="1200px"
      draggable
      @close="closeDialog"
    >
      <el-form ref="formRef" :model="formData" :inline="true" :rules="rules">
        <h4 class="mb-[20px] mt-[0px]">基本数据</h4>
        <div>
          <el-descriptions
            class="margin-top"
            title=""
            :column="3"
            size="large"
            border
          >
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">异常通知单号</div>
              </template>
              {{ formData.noticeCode }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">责任部门</div>
              </template>
              {{ formData.liableDepartmentName }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">状态</div>
              </template>
              {{ useDictionary("reworkStatus", formData.status) }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">设备</div>
              </template>
              {{ formData.equipName }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">产品型号</div>
              </template>
              {{ formData.productCode }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">产品名称</div>
              </template>
              {{ formData.productName }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">批次号</div>
              </template>
              {{ formData.batchNo }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">异常数量</div>
              </template>
              {{ formData.abnormalNum }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">比例%</div>
              </template>
              {{ formData.ratio }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <h4 class="mb-[20px] mt-[20px]">详细数据</h4>
        <div class="formTable2">
          <el-table
            :data="formData.details"
            style="width: 100%"
            :key="Math.random"
            border
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            />
            <el-table-column label="问题描述" props="describes" min-width="150">
              <template #default="{ $index, row }">
                {{ row.describes }}
              </template>
            </el-table-column>
            <el-table-column label="问题要求" props="demand" min-width="150">
              <template #default="{ $index, row }">
                {{ row.demand }}
              </template>
            </el-table-column>
            <el-table-column label="问题实际" props="actual" min-width="150">
              <template #default="{ $index, row }">
                {{ row.actual }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <h4 class="mb-[20px] mt-[20px]">
          {{
            viewType === 2
              ? "返工"
              : [3, 4].includes(viewType)
              ? "评估"
              : [6].includes(viewType)
              ? "报废"
              : "指导"
          }}意见
        </h4>
        <el-row>
          <el-col :span="24">
            <el-form-item label="" prop="viewContent" style="width: 99%">
              <el-input
                type="textarea"
                style="width: 100%"
                v-model="formData.viewContent"
                placeholder="请输入意见"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <h4 class="mb-[20px] mt-[20px]">上传附件</h4>
        <el-form-item label="" prop="files">
          <CommonUploadFile
            :showText="false"
            :key="uploadKey"
            :files="formData.files || []"
            @update-files="updateFormFiles"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="![3, 4, 6].includes(viewType)"
            type="primary"
            :loading="loading"
            @click="handleSubmit(1)"
            >返 工</el-button
          >
          <el-button
            v-if="![2, 5].includes(viewType)"
            type="primary"
            :loading="loading"
            @click="handleSubmit(0)"
            >确 定</el-button
          >
          <el-button
            v-if="viewType === 4"
            type="danger"
            :loading="loading"
            @click="dismissed"
            >驳 回</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import useEvent from "@/utils/useEvent";
import { useDictionary } from "../../../utils/useTable"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "OPENREWORKABNORMALDUTYNOTICEVIEW",
  inheritAttrs: false,
});

const { eventBusEmit, eventBusOn } = useEvent();
const emit = defineEmits(["reset-table", "change-visible"]);

const uploadKey = ref(Math.random());
const visible = ref(false);
const dialogTitle = ref("");
const page = ref("");
const data = reactive({});

const viewType = ref(0);

// 图片处理
function updateFormFiles(val: []) {
  formData.files = val;
}
/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  version: "",
  status: "",
  workStatus: "",
  noticeCode: "",
  noticeDate: "",
  noticeDepartmentCode: "",
  noticeDepartmentName: "",
  noticeDepartmentId: "",
  noticeUserId: "",
  noticeUserName: "",
  liableDepartmentId: "",
  liableDepartmentName: "",
  viewId: "",
  viewContent: "",
  viewUserName: "",
  viewTime: "",
  viewStatus: "",
  equipId: "",
  equipCode: "",
  equipName: "",
  productId: "",
  productCode: "",
  productName: "",
  materialNo: "",
  batchNo: "",
  abnormalNum: "",
  judgeUserName: "",
  judgeUserId: "",
  judgeTime: "",
  ratio: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
  details: [
    {
      id: "",
      version: "",
      noticeDocId: "",
      describes: "",
      demand: "",
      actual: "",
      remarks: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      enabled: "",
      deleted: "",
    },
  ],
});

const validateFiles = (rule, value) => {
  console.log(viewType.value);
  if ([2, 3, 4, 5].includes(viewType.value)) {
    if (!value) return Promise.reject("请选择文件");
  }
  return Promise.resolve();
};
/** rules规则 */
const rules = reactive({
  files: [
    {
      validator: validateFiles,
      trigger: "blur",
    },
  ],
});

const isValidated = ref(false);

const details = {
  id: "",
  version: "",
  noticeDocId: "",
  describes: "",
  demand: "",
  actual: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
};

/** 关闭表单弹窗 */
function closeDialog() {
  visible.value = false;
  emit("change-visible", false);
  uploadKey.value = Math.random();
  resetForm();
}
/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.id = "";
  formData.version = "";
  formData.status = "";
  formData.workStatus = "";
  formData.noticeCode = "";
  formData.noticeDate = "";
  formData.noticeDepartmentCode = "";
  formData.noticeDepartmentName = "";
  formData.noticeDepartmentId = "";
  formData.noticeUserId = "";
  formData.noticeUserName = "";
  formData.liableDepartmentId = "";
  formData.liableDepartmentName = "";
  formData.viewId = "";
  formData.viewContent = "";
  formData.viewUserName = "";
  formData.viewTime = "";
  formData.viewStatus = "";
  formData.equipId = "";
  formData.equipCode = "";
  formData.equipName = "";
  formData.productId = "";
  formData.productCode = "";
  formData.productName = "";
  formData.materialNo = "";
  formData.batchNo = "";
  formData.abnormalNum = "";
  formData.judgeUserName = "";
  formData.judgeUserId = "";
  formData.judgeTime = "";
  formData.ratio = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
}

const loading = ref(false);

const viewTypeList = [
  {
    name: "指导文件",
    viewType: 2,
    isRework: -1,
  },
  {
    name: "可行性评估",
    viewType: 3,
    viewStatus: 8,
    isRework: 0,
  },
  {
    name: "返工风险评估",
    viewType: 4,
    viewStatus: 9,
    isRework: 0,
  },
  {
    name: "返工作业指导书",
    viewType: 5,
    isRework: 1,
  },
  {
    name: "报废",
    viewType: 6,
    viewStatus: 3,
    isRework: 0,
  },
];

const dismissed = async () => {
  loading.value = true;
  const { id, viewContent, viewId, files } = formData;
  const text = "保存";
  const params = {
    id: viewId,
    noticeId: id,
    files,
    viewContent,
    isRework: 0,
    viewType: viewType.value,
    viewStatus: 7,
  };
  await saveViewDetail(params, text);
  isValidated.value = false;
};

/** 异常品通知单保存提交 */
function handleSubmit(isRework) {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const { id, viewContent, viewId, files } = formData;
      const find = viewTypeList.find(
        (item: any) => item.viewType === viewType.value
      );
      isRework = find.isRework === -1 ? isRework : find.isRework;
      const text = isRework ? "返工" : "保存";
      const params = {
        id: viewId,
        noticeId: id,
        files,
        viewContent,
        isRework,
        viewType: viewType.value,
        viewStatus: find?.viewStatus,
        pageType: page.value,
      };
      await saveViewDetail(params, text);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

const saveViewDetail = async (params, text) => {
  await request({
    url: "/qms/roknoticeviewdetail/saveViewDetail",
    method: "post",
    data: params,
  }).finally(() => {
    loading.value = false;
  });
  ElMessage.success(text + `成功`);
  closeDialog();
  eventBusEmit("RESET-REWORK-TABLE", formData.id);
};

async function getdetails() {
  let sondetails = await request({
    url: "/qms/roknoticedoc/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}

async function getInstructionRework() {
  let { data } = await request({
    url: "/qms/roknoticeviewdetail/getOneByType",
    method: "post",
    data: { noticeId: formData.id, viewType: viewType.value },
  }).finally(() => {
    loading.value = false;
  });
  formData.viewContent = data?.viewContent;
  formData.viewId = data?.id;
  if (formData.viewId) {
    await getFiles(formData.viewId);
  }
}

async function getFiles(viewId) {
  let sondetails = await request({
    url: "/qms/rokmonitorworkfile/getFiles",
    method: "post",
    data: { monitorWorkId: viewId, monitorWorkFileType: viewType.value },
  }).finally(() => {
    loading.value = false;
  });
  formData.files = sondetails.data;
  uploadKey.value = Math.random();
}

let openEvent;
onBeforeUnmount(() => {
  openEvent();
});
onMounted(() => {
  openEvent = eventBusOn(
    "OPEN-REWORK-ABNORMAL-DUTY-NOTICE-VIEW",
    async ({ row, type, title, pageType }) => {
      Object.assign(formData, row);
      viewType.value = type;
      dialogTitle.value = title;
      page.value = pageType;
      await getdetails();
      if (type === 2) {
        await getInstructionRework();
      }
      visible.value = true;
    }
  );
});
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}

// .formTable {
//   :deep(.el-form-item) {
//     margin-right: 0 !important;
//   }
// }

:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}

:deep.el-input.el-input--default.el-input--suffix {
  // 固定宽度
  width: 190px !important;
}
</style>
